﻿using CommandLine;
using CommandLine.Text;
using PBIW.Console;
using PBIW.Console.Commands;
using PBIW.Core;

const string applicationId = "PlumBlossomInWinter.Console";

#region Core
CoreStartingStates state = Core.Start(new(applicationId, AppContext.BaseDirectory), out var core);

if (!state.IsFullySucceeded())
{
    var most = state.ToLevels().TheMostSevere();
    if (most is CoreStartingStateLevels.SoSevereError)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"发生了灾难性错误！重新安装 {applicationId} 或可解决。");
        Environment.Exit((int)state);
        return;
    }

    var errors = state.ToProblemsAndErrors();
    if (errors.HasFlag(CoreStartingProblemsAndErrors.AutoDisabledZhouyiReferencing))
    {
        Console.ForegroundColor = ConsoleColor.DarkYellow;
        Console.WriteLine($"警告：无法读取《周易》或其象传彖传，此功能将自动关闭。");
    }

    if (errors.HasFlag(CoreStartingProblemsAndErrors.CannotReadOrWriteSettings))
    {
        Console.ForegroundColor = ConsoleColor.DarkRed;
        Console.WriteLine($"错误：无法写入配置文件。请检查文件权限。");
    }

    if (most is CoreStartingStateLevels.SevereError)
    {
        Console.ForegroundColor = ConsoleColor.DarkRed;
        Console.WriteLine($"程序将自行停止运行，请尝试修复以上错误后重新运行……");
        return;
    }

    Console.ResetColor();
}

#endregion Core

var commands = new Dictionary<Type, IExecutor>() {
    { typeof(CastCommand.Options), new CastCommand.Executor(core) },
    { typeof(ConfigCommand.Options), new ConfigCommand.Executor(core) },
    { typeof(ReferCommand.Options), new ReferCommand.Executor(core) },
    { typeof(VersionCommand.Options), new VersionCommand.Executor(core) },
};

var keys = commands.Keys.ToArray();

SentenceBuilder.Factory = () => new SentenceBuilderInChinese();
var parser = new Parser(with =>
{
    with.AutoVersion = false;
    with.HelpWriter = null;
});

var parserResult = parser.ParseArguments(args, keys);

parserResult.WithNotParsed(errs =>
{
    Func<HelpText, HelpText> onErrorFunc = (h) =>
    {
        h.AdditionalNewLineAfterOption = true;
        h.Heading = string.Empty;
        h.Copyright = string.Empty;
        h.AutoHelp = true;
        h.AutoVersion = false;
        h.MaximumDisplayWidth = 60;
        return HelpText.DefaultParsingErrorsHandler(parserResult, h);
    };

    HelpText helpText =
    errs.Count() is 1 && errs.Single() is HelpVerbRequestedError ?
    HelpText.AutoBuild(parserResult, onErrorFunc) :
    HelpText.AutoBuild(parserResult, onErrorFunc, onExample: e => e);
    // 如果传入了参数 onExample 则不能正常显示 help verb 的内容；
    // 如果不传入，则不能正常显示错误。
    // 故做一判断将其分离。

    Console.WriteLine(helpText);
});

parserResult.WithParsed(value =>
{
    Console.WriteLine("命令解析成功，即将开始执行。");
    commands[parserResult.TypeInfo.Current].Execute(value);
});